package com.demo.springsecuritystudy.service.impl;

import com.demo.springsecuritystudy.service.SecurityService;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

//@Service
public class SecurityServiceImpl implements SecurityService {

    @Override
    public Boolean hasPermission(HttpServletRequest httpServletRequest,
                                 Authentication authentication) {
        // 获取主体
        Object object = authentication.getPrincipal();
        if (object instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) object;
            // 获取权限
            Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
            // 判断权限是否存在对应的URI
            return authorities.contains(new SimpleGrantedAuthority(httpServletRequest.getRequestURI()));
        }
        return false;
    }
}
